<template>
  <div>
    <div class="box-top">
      <div class="search-container">
        <el-form :model="searchForm" :inline="true" label-suffix=":" size="medium">
          <el-form-item label="断面类型" style="margin-bottom: 0;">
            <!-- 筛选条件 -->
            <el-select v-model="searchForm.dmlaiyuan" placeholder="请选择断面类型" @change="handleSearch" style="width: 100%">
              <!-- 添加选项 -->
              <el-option label="全部" value="all"></el-option>
              <el-option label="国控断面" value="国控断面"></el-option>
              <el-option label="市控断面" value="市控断面"></el-option>
              <el-option label="区控断面" value="区控断面"></el-option>
              <!-- 可以根据你的需求添加更多选项 -->
            </el-select>
          </el-form-item>
          <el-form-item label="所在流域" style="margin-bottom: 0;">
            <el-select v-model="searchForm.liuyu" placeholder="请选择所在流域" @change="handleSearch" style="width: 100%" filterable>
              <!-- 添加流域选项 -->
              <el-option label="全部" value="all"></el-option>
              <template v-for="item in liuyuList">
                <el-option :label="item.label" :value="item.value" :key="item.label"></el-option>
              </template>
              <!-- 可以根据你的需求添加更多选项 -->
            </el-select>
          </el-form-item>
          <el-form-item label="断面名称" style="margin-bottom: 0;">
            <el-input v-model="searchForm.dmmc" placeholder="请输入关键字" @clear="handleSearch" clearable></el-input>
          </el-form-item>
          <el-form-item style="margin-bottom: 0;">
            <el-button type="primary" @click="handleSearch" style="margin-right: 0">搜索</el-button>
            <el-button type="warning" @click="handleClear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 新增按钮 -->
      <div>
        <el-button type="success" @click="handadd" size="medium">新增</el-button>
      </div>
    </div>

    <el-table v-loading="loading" element-loading-text="拼命加载中" :data="pagedData" border style="width: 100%"
      size="medium" :max-height="height" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column label="序号" type="index" width="60px" align="center" />
      <el-table-column prop="dmmc" label="断面名称" />

      <el-table-column prop="xzqhname" label="旗区名称" show-overflow-tooltip />
      <el-table-column prop="szmb" label="水质目标" show-overflow-tooltip />
      <el-table-column prop="dmlaiyuan" label="断面类型" show-overflow-tooltip />
      <el-table-column prop="dmquanzhong" label="断面权重" show-overflow-tooltip />
      <!-- <el-table-column prop="jianceshijian" label="监测时间" /> -->
      <el-table-column prop="liuyu" label="所在流域" />
      <el-table-column prop="action" label="操作" width="170" align="center">
        <template slot-scope="scope">
          <!-- 操作按钮 -->
          <el-button type="primary" size="mini" @click="handedit(scope.row)">
            修改
          </el-button>
          <el-button type="danger" size="mini" @click="deleteItem(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="bottom">
      <el-pagination :current-page="currentPage" background layout="total, prev, pager, next, jumper"
        :total="totalItems" :page-size="pageSize" @current-change="handleCurrentChange" hide-on-single-page />
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :modal-append-to-body="false" top="10vh" width="500px">
      <el-form :model="formData" label-position="left" label-width="106px" size="medium" :rules="rules" ref="myForm"
        style="margin-top: -15px; margin-bottom: -20px" hide-required-asterisk>
        <!-- 断面名称 -->
        <el-form-item label="断面名称" prop="dmmc">
          <el-input v-model="formData.dmmc" />
        </el-form-item>

        <!-- 旗区名称 -->
        <el-form-item label="旗区名称" prop="xzqhcode">
          <el-select v-model="formData.xzqhcode" placeholder="请选择" filterable style="width: 100%" :disabled="isEditable"
            @change="handxzqh">
            <el-option v-for="option in xzqhOptions" :key="option.value" :label="option.label"
              :value="option.value"></el-option>
          </el-select>
        </el-form-item>

        <!-- 水质目标 -->
        <el-form-item label="水质目标" prop="szmb">
          <el-select v-model="formData.szmbdm" placeholder="请选择" style="width: 100%" @change="handszmb">
            <el-option v-for="item in szmbOptions" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <!-- 断面责任权重 -->
        <el-form-item label="断面责任权重" prop="dmquanzhong">
          <el-select v-model="formData.dmquanzhong" placeholder="请选择" style="width: 100%">
            <el-option label="0.5" value="0.5"></el-option>
            <el-option label="1" value="1"></el-option>
          </el-select>
        </el-form-item>

        <!-- 断面流域 -->
        <el-form-item label="所在流域" prop="liuyu">
          <el-select v-model="formData.liuyu" placeholder="请选择所在流域" style="width: 100%" filterable>
            <template v-for="item in liuyuList">
              <el-option :label="item.label" :value="item.value" :key="item.label"></el-option>
            </template>
          </el-select>
        </el-form-item>

        <!-- 断面类型 -->
        <el-form-item label="断面类型" prop="dmlaiyuan">
          <el-select v-model="formData.dmlaiyuan" placeholder="请选择断面类型" style="width: 100%" @change="handmlaiyuan">
            <el-option label="国控断面" value="国控断面"></el-option>
            <el-option label="市控断面" value="市控断面"></el-option>
            <el-option label="区控断面" value="区控断面"></el-option>
          </el-select>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input v-model="formData.bz" type="textarea" :rows="2" placeholder="备注" />
        </el-form-item>
        <el-form-item label-width="0" style="text-align: center">
          <el-button type="primary" @click="onSubmit"> 保 存 </el-button>
          <el-button @click="dialogVisible = false"> 关 闭 </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import options from "@/utils/options";
import config from "@/config/config";
import { GetPermission } from "@/utils/auth";
export default {
  name: "InterfaceManagement",
  data() {
    return {
      height: 300,
      loading: true,

      searchForm: {
        // 筛选条件的表单数据
        dmlaiyuan: "all",
        liuyu: "all",
        dmmc: "",
      },
      initialData: [],//初始数据
      allData: [], // 所有数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数据量
      totalItems: 0, // 总项目数
      formData: {
        bz: null,
        createtime: null,
        dmlaiyuan: null,
        dmmc: null,
        dmquanzhong: null,
        id: null,
        jianceshijian: null,
        liuyu: null,
        szmb: null,
        szmbdm: null,
        xzqhcode: null,
        xzqhname: null,
      },
      dialogVisible: false,
      title: "添加断面信息",
      liuyuList: [],
      szmbOptions: [],
      isEditable: true,
      rules: {
        dmmc: [{ required: true, message: "请输入断面名称", trigger: "blur" }],
        xzqhcode: [
          { required: true, message: "请选择旗区名称", trigger: "change" },
        ],
        szmb: [
          { required: true, message: "请选择水质目标", trigger: "change" },
        ],
        dmquanzhong: [
          { required: true, message: "请选择断面责任权重", trigger: "change" },
        ],
        // liuyu: [
        //   { required: true, message: "请选择断面流域", trigger: "change" },
        // ],
        dmlaiyuan: [
          { required: true, message: "请选择断面类型", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    // 计算分页后的数据
    pagedData() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.allData.slice(startIndex, endIndex);
    },
  },

  created() {
    const height = window.innerHeight - 185;
    this.height = height;
    this.liuyuList = options.liuyuArray;
    this.szmbOptions = config.typeArray;
    this.xzqhOptions = config.xzqhArray;
    this.isEditable = GetPermission().areacode == "1506" ? false : true;
    this.fetchData(GetPermission().areacode);
  },
  methods: {
    fetchData(xzqh) {
      this.$api
        .getNDminfoByXzqh(xzqh)
        .then((response) => {
          console.log("拿到的数据", response);
          this.allData = response.data.data; // 保存所有数据
          this.totalItems = this.allData.length; // 设置总条数
          this.currentPage = 1; // 每次获取数据后重置当前页码为第一页
          this.initialData = response.data.data;
        })
        .finally(() => {
          this.loading = false; // 请求完成后设置加载状态为 false
        });
    },
    handleSelectionChange(val) {
      this.selection = val;
    },

    handleSearch() {
      let data = this.initialData;
      if (this.searchForm.dmlaiyuan != 'all') {
        data = data.filter(item => item.dmlaiyuan == this.searchForm.dmlaiyuan);
      }
      if (this.searchForm.liuyu != 'all') {
        data = data.filter(item => item.liuyu == this.searchForm.liuyu);
      }
      if (this.searchForm.dmmc) {
        data = data.filter(item => item.dmmc.indexOf(this.searchForm.dmmc.trim()) !== -1);
      }
      this.allData = data;
      this.currentPage = 1;
      this.totalItems = this.allData.length;
    },

    handleClear() {
      // 清空搜索条件
      this.searchForm = {
        dmlaiyuan: "all",
        liuyu: "all",
        dmmc: "",
      };
      this.allData = this.initialData;
      this.currentPage = 1;
      this.totalItems = this.allData.length;
    },
    deleteItem(id) {
      console.log("删除id", id);

      try {
        this.$confirm("确定要删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            // 用户点击了确定按钮
            console.log("用户点击了确定按钮");
            this.$api
              .deleteNDminfo(id)
              .then((response) => {
                // 处理接口返回的数据或其他逻辑

                // 处理删除成功的情况
                console.log("删除成功", response.data);
                this.allData = this.allData.filter((item) => item.id !== id);
                this.totalItems--; // 减少总项目数

                // 更新分页后的数据
                // 更新分页后的数据

                // 更新分页组件的总项目数和当前页码
                this.totalItems = this.allData.length;
                // 如果删除后当前页没有数据了，需要将当前页码减一
                if (this.pagedData.length === 0 && this.currentPage > 1) {
                  this.currentPage--;
                }
                //  重新获取数据
                // this.fetchData();
              })
              .catch((error) => {
                // 处理失败的情况
                console.error("失败:", error);
              });
          })
          .catch(() => {
            // 用户点击了取消按钮
            console.log("用户点击了取消按钮");
          });
      } catch (error) {
        // 处理删除失败的情况
        console.error("删除失败", error);
      }
    },

    handleCurrentChange(val) {
      // 当用户切换分页时触发
      this.currentPage = val;
    },
    // 行政区划
    handxzqh(val) {
      this.formData.xzqhname = config.xzqhArray.find(item => item.value == val).label;
    },
    // 水质目标
    handszmb(val) {
      this.formData.szmb = config.typeArray.find(item => item.value == val).label;
    },
    // 断面来源
    handmlaiyuan(val) {
      if (val == '区控断面') {
        this.formData.jianceshijian = '季度';
      } else {
        this.formData.jianceshijian = '月';
      }
    },
    handadd() {
      this.title = "添加断面信息";
      this.formData = {
        bz: null,
        createtime: new Date(),
        dmlaiyuan: "国控断面",
        dmmc: null,
        dmquanzhong: 1,
        id: null,
        jianceshijian: '月',
        liuyu: "",
        szmb: config.typeArray.find(item => item.value == 1).label,
        szmbdm: 1,
        xzqhcode: GetPermission().areacode,
        xzqhname: config.xzqhArray.find(item => item.value == GetPermission().areacode).label,
      };
      this.$nextTick(() => {
        this.dialogVisible = true;
      });
    },
    handedit(data) {
      console.log(data);
      this.title = "修改断面信息";
      this.formData = {
        bz: data.bz,
        createtime: new Date(),
        dmlaiyuan: data.dmlaiyuan,
        dmmc: data.dmmc,
        dmquanzhong: data.dmquanzhong,
        id: data.id,
        jianceshijian: data.jianceshijian,
        liuyu: data.liuyu,
        szmb: data.szmb,
        szmbdm: data.szmbdm,
        xzqhcode: data.xzqhcode,
        xzqhname: data.xzqhname,
      };
      this.$nextTick(() => {
        this.dialogVisible = true;
      });
    },
    onSubmit() {
      this.$refs.myForm.validate((valid) => {
        if (valid) {
          if (!this.formData.id) {
            this.$api
              .addNDminfo(this.formData)
              .then((res) => {
                console.log("新增成功", res);
                if (res.data.code == 0) {
                  this.fetchData(GetPermission().areacode);
                  this.$message.success("断面添加成功！");
                  this.dialogVisible = false;
                } else {
                  this.$message.error("断面添加失败！");
                }
              })
              .catch(() => {
                this.$message.error("断面添加失败！");
              });
          } else {
            this.$api
              .editNDminfo(this.formData)
              .then((res) => {
                if (res.data.code == 0) {
                  this.fetchData(GetPermission().areacode);
                  this.$message.success("断面信息修改成功！");
                  this.dialogVisible = false;
                } else {
                  this.$message.error("断面信息修改失败！");
                }
              })
              .catch(() => {
                this.$message.error("断面信息修改失败！");
              });
          }
        }
      });

      // if (!this.formData.dmmc) {
      //   this.$message.error("断面名称不能为空");
      //   return;
      // }
    },
  },
};
</script>

<style scoped>
/* 这里可以添加针对 InterfaceManagement 页面的样式 */
.box-top {
  padding: 10px;
  background-color: rgb(232, 232, 232);
  overflow: hidden;
  text-align: center;
  /* margin-bottom: 10px; */
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-container>* {
  margin-right: 10px;
}

.bottom {
  text-align: right;
}
</style>
